<template>
  <transition name="fade" @after-leave="handleAfterLeave">
    <div class="toast" v-if="isVisible" >
      <slot>{{ message }}</slot>
    </div>
  </transition>
</template>
<script setup>
import { defineProps, onMounted, onUnmounted, defineEmits,ref } from "vue";
const props = defineProps(["message", "duration"]);
const emit = defineEmits(["destroy"]);
const isVisible = ref(false);
let timer;
onMounted(() => {
  //当组件挂载完成后，把isVisible设置为true
  isVisible.value = true;
  timer = setTimeout(() => {
    isVisible.value = false;
    //如果加上动画后就不能在这里发射事件,应该在离开动画结束后触发此事件，移除DOM
  }, props.duration);
});
onUnmounted(() => {
  if (timer) clearTimeout(timer);
});
const handleAfterLeave  = ()=>{
 emit('destroy');
}
</script>
<style scoped>
.toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 5px 20px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  border-radius: 5px;
  text-align: center;
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 1s;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
